﻿
using AutoMapper;
using Gengens.Disk.Entity.entity.file;
using Gengens.Disk.Service.service;
using Gengens.Disk.WebApi.dto.input.file;
using Gengens.Disk.WebApi.dto.output;
using Gengens.Disk.WebApi.dto.output.file;
using Gengens.Disk.WebApi.util;
using Microsoft.AspNetCore.Mvc;

namespace Gengens.Disk.WebApi.Controllers.file
{

    public class FilesController : BaseUserController
    {
        private readonly ILogger<FilesController> _logger;
        private readonly DataInfoService _dataInfoService;

        public FilesController(ILogger<FilesController> logger,DataInfoService dataInfoService)
        {
            _logger = logger;
            _dataInfoService = dataInfoService;
        }

        [HttpPost("prefile")]
        public ApiRet PreFileUpload(PreFileForCreateDto createDto) {
            var pre = new PreFileInfo(createDto,UserId,Username);
            FileUtils.PreFileCache.Add(pre);
            return ApiRet.Ok("准备完毕", pre.Id);
        }


        [HttpPost("split")]
        public async Task<ApiRet> SplitUpload(IFormFile file,Guid id) {
            var pre = FileUtils.PreFileCache.FirstOrDefault(p => p.Id == id);
            if (pre == default) return ApiRet.Fail("没有前置信息");
            if (pre.UserId != UserId) return ApiRet.Fail("无权上传");

            using (var fs = System.IO.File.Open(pre.Url, FileMode.Append))
            {
                await file.CopyToAsync(fs);
            }
            pre.UpdateTime = DateTime.Now;
            pre.ExecutedCount++;
            if (pre.ExecutedCount != pre.SplitCount) {
                return ApiRet.Ok(string.Empty,default,201);
            }

            FileUtils.PreFileCache.Remove(pre);
            DataInfo data = new DataInfo(pre.Url,pre.Name,UserId);
            await _dataInfoService.InsertAsync(data);
            await _dataInfoService.SaveChanegsAsync();
            return ApiRet.Ok("资源上传完毕", data);
        }
    }
}
